#coding=utf-8
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
import utils
import simplejson
import mock
import logging
import os
from templatetags.bvapp import join_by_name, millions, join_indication_or_disease

class AmgenRetrieverMock(utils.RetrieverInterface):
    def query(self, query):
        return self
    def get(self):
        filename = os.path.join(os.path.dirname(__file__),
                                'fixtures',
                                'freebase_response.txt')
        f = open(filename, 'r')
        s = ''.join(f.readlines())
        f.close()
        return simplejson.loads(s)

class ReportsTest(TestCase):

    def setUp(self):
        class FreeBaseRetriever(utils.RetrieverInterface):
            def set(self, response):
                self.response = response
            def get(self):
                return self.response
        self.client = Client()
        self.r = utils.FreeBaseRetriever()
        self.amgen = utils.Company(AmgenRetrieverMock(), '/en/amgen')

    def test_ajax_should_work(self):
        c = self.client.get(reverse('company_ajax',
                kwargs={'emitter_format': 'json'}))
        self.assertEquals(c.status_code, 200)

    def test_read_should_work(self):
        c = self.client.get(reverse('company_read', args=('en/amgen',)))
        self.assertEquals(c.status_code, 200)
        self.assertTemplateUsed(c,
            'bvsearchapp/topics/company_read.html')

    def test_set_retriever(self):
        class InvalidRetirever(object):
            pass
        self.assertRaises(TypeError, utils.Company, InvalidRetirever,\
            '/en/amgen/')

    def test_title(self):
        self.assertEquals(self.amgen.title, 'Amgen')

    def test_invalid_title(self):
        self.assertRaises(utils.InvalidCompanyID, utils.Company, self.r, '/en/fdfdf')

    def test_article(self):
        overview_head = \
            ''.join(('Amgen Inc. (NASDAQ: AMGN, SEHK: 4332) is an ',
                     'international biotechnology company ',
                     'headquartered in Thousand Oaks'))
        overview_tail = 'Neupogen (the company\'s first products on the...'
        self.assert_(self.amgen.overview.startswith(overview_head))
        self.assert_(self.amgen.overview.endswith(overview_tail))        

    def test_areas_of_expertise(self):
        areas = \
            ''.join(('<a href="/technology/en/monoclonal_antibodies">',
                     'Monoclonal Antibody</a>, <a href="/technology/en',
                     '/small_molecule">Small molecule</a>, ',
                     '<a href="/technology/en/therapeutics">',
                     'Therapeutics</a>'))
        self.assertEquals(self.amgen.areas_of_expertise, areas)

    def test_medical_focus(self):
        medical_focuses = \
            ''.join(('<a href="/disease/en/anemia">Anemia</a>, ',
                     '<a href="/disease/en/cardiovascular_disease">',
                     'Cardiovascular disease</a>, ',
                     '<a href="/disease/en/cancer">Cancer</a>, ',
                     '<a href="/disease/guid/9202a8c04000641f8',
                     '00000000998a9db"></a>, ',
                     '<a href="/disease/en/breast_cancer">Breast cancer',
                     '</a>, <a href="/disease/en/prostate_cancer">',
                     'Prostate cancer</a>'))
        self.assertEquals(self.amgen.medical_focuses, medical_focuses)

    def test_date_founded(self):
        self.assertEquals(self.amgen.date_founded, '1980')

    def test_headquarters(self):
        headquarters = \
            'ONE AMGEN CENTER DRIVE, Thousand Oaks, California, 91320'
        self.assertEquals(self.amgen.headquarters, headquarters)

    def test_industries(self):
        industries = 'Biotechnology, Biological Product (except Diagnostic) Manufacturing'
        self.assertEquals(self.amgen.industries, industries)

    def test_webpages(self):
        webpages = '<a href="http://www.amgen.com/">http://www.amgen.com/</a>'
        self.assertEquals(self.amgen.webpages, webpages)

    def test_company_type(self):
        self.assertEquals(self.amgen.company_type, 'Publicly listed company')

    def test_ticker_symbol(self):
        # Only NASDAQ support
        # http://www.wikinvest.com/stock/Amgen_%28AMGN%29/Data/Key_Metrics
        self.assertEquals(self.amgen.ticker_symbol, 'AMGN')

    def test_investment_round(self):
        c = utils.Company(self.r, '/en/vaxinnate')
        self.assertEquals(c.investment_round['date'], '2009-03-26')
        self.assertEquals(c.investment_round['amount_raised'], 30000000)
        self.assertEquals(c.investment_round['investors'], 'New Leaf '+
                                             'Venture Partners, '+
                                             'MedImmune Ventures Inc., Canaan Partners, CHL '+
                                             'Medical Partners, Oxford '+
                                             'Biosciences Partners, '+
                                             'HealthCare '+
                                             'Ventures')
        self.assertEquals(c.investment_round['web_reference'],
                          'http://www.pehub.com/35492/vaxinnate-raising-30-million/')

    def test_products(self):
        self.assertEquals(self.amgen.products[0]['name'], 'Panitumumab')
        self.assertEquals(self.amgen.products[-1]['name'], 'Romiplostim')

    def test_therapeutics_on_the_market(self):
        self.assertEquals(self.amgen.therapeutics_on_the_market[0]['name'], 'Panitumumab')
        self.assert_(len(self.amgen.therapeutics_on_the_market[0]['indication_or_disease'])>0)
        self.assertEquals(self.amgen.therapeutics_on_the_market[-1]['name'], 'AMG 714')

    def test_products_on_the_market(self):
        self.assertEquals(len(self.amgen.products_on_the_market), 0)

    def test_therapeutics_in_development(self):
        self.assertEquals(self.amgen.therapeutics_in_development[0]['name'], 'Romiplostim')
        self.assertEquals(self.amgen.therapeutics_in_development[-1]['name'], 'Romiplostim')

    def test_products_in_development(self):
        self.assertEquals(self.amgen.products_in_development[0]['name'], 'Kepivance')
        self.assert_(self.amgen.products_in_development[0]['article']\
            .startswith('Kepivance is a form of keratinocyte growth factor (KGF) that is made in the laboratory'))

    def test_logo(self):
        self.assertEquals(self.amgen.logo['id'], '/wikipedia/images/en_id/4609692')
        self.assertEquals(self.amgen.logo['url'], 'http://freebase.com/api/trans/image_thumb/wikipedia/images/en_id/4609692')

    def test_templatefilter_join_by_name(self):
        self.assertEquals(
            join_by_name(
                [{u'id': u'/en/amgen', u'name': u'Amgen'},
                 {u'id': u'/en/foo', u'name': u'Foo'}]),
            'Amgen, Foo')

    def test_templatefilter_millions(self):
        self.assertEquals(
            millions(170500000),
            171)
        self.assertEquals(millions('foo'), '-')        


    def test_templatefilter_join_indication_or_disease(self):
        self.assertEquals(
            join_indication_or_disease(
                self.amgen.therapeutics_on_the_market[1]['indication_or_disease']),
            'On the market for Anemia')
            

class FreeBaseRetrieverTest(TestCase):

    @mock.patch('freebase.mqlread')
    def test_retriever(self, mock):
        """
        Tests FreeBaseRetriever class from utils package.
        Class retrieves infromation from freebase and store it in cache
        """
        mock.return_value = list(simplejson.loads(
            """[{
                "id":   "/en/amgen",
                "name": "Amgen",
                "type": "/base/bioventurist/science_or_technology_company"
              }]"""))
        query = \
            [{
              'type': '/base/bioventurist/science_or_technology_company',
              'id': '/en/amgen',
              'name': None
            }]
        r = utils.FreeBaseRetriever()
        response = r.query(query).get()
        self.assertEquals(mock.call_args[0][0], query)
        self.assertEquals(response[0]['name'], 'Amgen')
        # Check returned value is cached
        response = r.query(query).get()
        self.assertEquals(response[0]['name'], 'Amgen')
        self.assertEquals(mock.call_count, 1)

